package com.nexgo.payment.pack;

import android.text.TextUtils;

import com.nexgo.common.ByteUtils;
import com.nexgo.common.TlvUtils;
import com.nexgo.data.entity.SendData;
import com.nexgo.data.entity.SendDataBuilder;
import com.nexgo.payment.constrant.CardMode;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.databases.TransRecord;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.util.MessageHelper;
import com.nexgo.payment.util.StringUtils;

import java8.util.Optional;

/**
 * 预授权完成撤销组包
 * <p>
 * Created by wanghongyang on 2017/8/24.
 */
class PreAuthComVoidBuilder extends DataBuilder {

    private final TransRecord mTransRecord;

    PreAuthComVoidBuilder(TransData transData, DataSource repository) {
        super(transData, repository);
        mTransRecord = mRepository.queryTransRecord(mTransData.getOrgTraceNum());
    }

    @Override
    public SendData form() {
        boolean isTrackEncrypt = "1".equals(mRepository.getParamValue(PreferencesConstants.TRACK_ENCRYPTED));
        int mKeyIdx = Integer.parseInt(StringUtils.firstNonEmpty(mRepository.getParamValue(PreferencesConstants.MASTER_KEY_INDEX), "0"));
        boolean isDes = "0".equals(mRepository.getParamValue(PreferencesConstants.MASTER_KEY_ALGORITHM));
        String track;
        SendData sendData = new SendDataBuilder().setListener(mListener).setSignListener(mSignListener).createSendData();
        sendData.setHeader(MessageHelper.formMessageHeader(mRepository.getParamValue(PreferencesConstants.TPDU)));
        sendData.setMsgType(mTransData.getTransType().getMsgType());
        sendData.setPan(mTransData.getPan());
        sendData.setProcCode(mTransData.getTransType().getProcCode());
        sendData.setAmount(StringUtils.leftPad(mTransRecord.getAmount(), 12, '0'));
        sendData.setTraceNum(mRepository.getParamValue(PreferencesConstants.TRACE_NUMBER));
        //        wzp add 方便62域组数据
        setCurruntTraceNumber(mRepository.getParamValue(PreferencesConstants.TRACE_NUMBER));
        mRepository.increaseTraceNumber();
        sendData.setExpDate(mTransRecord.getExpDate());
        sendData.setEntryMode(mTransData.getEntryMode());
        sendData.setCsn(TextUtils.isEmpty(mTransData.getCsn()) ? mTransRecord.getCsn() : mTransData.getCsn());
        sendData.setConditionCode(mTransData.getTransType().getConditionCode());

        track = mTransData.getTk2();
        if (!TextUtils.isEmpty(track)) {
            track = track.replace('=', 'D');
            if (!isDes && isTrackEncrypt) {
                sendData.setTrack2(MessageHelper.trackEncrypt(track, mKeyIdx));
            } else {
                sendData.setTrack2(track);
            }
        }
        track = mTransData.getTk3();
        if (!TextUtils.isEmpty(track)) {
            track = track.replace('=', 'D');
            if (!isDes && isTrackEncrypt) {
                sendData.setTrack3(MessageHelper.trackEncrypt(track, mKeyIdx));
            } else {
                sendData.setTrack3(track);
            }
        }
        //37
//        sendData.setRefNum(mTransRecord.getRefNum());
        //38
        sendData.setAuthCode(StringUtils.rightPad(mTransData.getOrgAuthCode(), 6, ' '));
        sendData.setTerminalId(mTransRecord.getTerminalId());
        sendData.setMerchantId(mTransRecord.getMerchantId());
        sendData.setFundType(mTransRecord.getFundType());
        sendData.setPin(ByteUtils.byteArray2HexString(mTransData.getPin()));

        StringBuilder sb = new StringBuilder();
        sb.append("2");
        sb.append((!isDes && isTrackEncrypt)? "0" : "6");
        sendData.setScrtCtrlInfo(sb.toString());

        sendData.setField59(formField59());
        sendData.setField60(formField60());
        sendData.setField62(formField62());
        sendData.setMac("0000000000000000");
        return sendData;
    }


    private String formField60() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format(SysConstant.LOCALE, "%02d",
                Integer.parseInt(StringUtils.firstNonEmpty(mRepository.getParamValue(PreferencesConstants.CURRENT_OPERATOR_NO), "1"))));
        sb.append("0000");
        sb.append("6");
        sb.append(mTransData.isFallback() ? "2" : "0");
        if(!TextUtils.isEmpty(mTransData.getResultTlv())){
            String value  = Optional.ofNullable(TlvUtils.decodingTLV(mTransData.getResultTlv(), "84"))
                    .map(strings -> {
                        if (strings.size() == 0) {
                            return TlvUtils.decodingTLV(mTransData.getResultTlv(), "9f06");
                        } else {
                            return strings;
                        }
                    })
                    .map(strings -> strings.size() == 0 ? "" : strings.get(0))
                    .orElse("").toUpperCase();
            sb.append(value);
        }
        return ByteUtils.byteArray2HexString(sb.toString().getBytes());
    }


    public String formField62() {
        StringBuilder sb = new StringBuilder();
//        sb.append(mTransData.getTransType().getFuncCode());
        sb.append(StringUtils.firstNonEmpty(mTransRecord.getBatchNum(), "000000"));
        sb.append(getCurruntTraceNumber());
        sb.append(StringUtils.firstNonEmpty(mTransRecord.getTraceNum(), "000000"));
        return sb.toString();
    }

    /**
     * 判断是否手输卡号
     *
     * @return
     */
    private boolean isManualCardNo(){
        return mTransData.getCardMode() == CardMode.MANUAL;
    }
}
